package com.wonghiu.framework.cluster.directory.imp;

import com.wonghiu.framework.cluster.loadbalance.LoadBalance;
import com.wonghiu.framework.common.enums.HRpcErrorMessageEnum;
import com.wonghiu.framework.common.exception.HRpcException;
import com.wonghiu.framework.common.extention.ExtensionLoader;
import com.wonghiu.framework.common.factory.SingletonFactory;
import com.wonghiu.framework.exchange.HRpcRequest;
import com.wonghiu.framework.registry.zk.util.CuratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Author wonghiu
 * @Date 2021/8/11 18:28
 * @Version 1.0.1
 */
@Slf4j
public class ServiceDirectory {
    private final LoadBalance loadBalance;

    public ServiceDirectory() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("consist");
    }
    public List<String> getServiceUrlList(HRpcRequest rpcRequest){
        String rpcServiceName = rpcRequest.getRpcServiceName();
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
        if (serviceUrlList == null || serviceUrlList.size() == 0) {
            throw new HRpcException(HRpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        return serviceUrlList;
    }
    public InetSocketAddress lookupService(HRpcRequest rpcRequest) {
        List<String> serviceUrlList = getServiceUrlList(rpcRequest);
        // load balancing
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList, rpcRequest);
        log.info("Successfully found the service address:[{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}
